package com.meelive.ingkee.push.common;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.core.app.NotificationManagerCompat;

import android.text.TextUtils;
import android.util.Log;

import com.meelive.ingkee.push.InkePushConfig;
import com.meelive.ingkee.push.model.Constance;
import com.meelive.ingkee.push.model.InkePushType;
import com.meelive.ingkee.push.model.ReceiverInfo;
import com.meelive.ingkee.push.model.ReceiverType;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.List;

import static com.meelive.ingkee.push.model.Constance.TAG;

/**
 * Create by: fanfeiyue
 * on: 2019-08-22
 * desc:
 */
public class PushUtils {

    public static boolean DEBUG = false;

    public static String getDeviceManufacturer() {
        String line = "";
        BufferedReader input = null;
        String propName = "ro.miui.ui.version.name";

        try {
            Process p = Runtime.getRuntime().exec("getprop " + propName);
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException var12) {
            Log.e("DeviceUtils", "Unable to read sysprop " + propName);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException var11) {
                    ;
                }
            }
        }

        if (!TextUtils.isEmpty(line)) {
            return "XIAOMI";
        }

        String manufacturer = Build.MANUFACTURER.replace("-", "_");
        return manufacturer.toUpperCase();
    }

    public static boolean isSupportPush(InkePushType pushType, InkePushConfig pushConfig) {
        boolean support = false;
        String os = PushUtils.getDeviceManufacturer();
        if (DEBUG) {
            Log.d(TAG, "PushUtils Current device manufacturer: " + os);
        }

        switch (pushType) {
            case MIPUSH:
                support = os.contains("XIAOMI");
                break;
            case OPPOPUSH:
                support = os.contains("OPPO") || os.contains("ONEPLUS") || os.contains("REALME");
                break;
            case VIVOPUSH:
                support = os.contains("VIVO");
                break;
            case MEIZUPUSH:
                support = os.contains("MEIZU");
                break;
            case HMSPUSH:
                support = os.contains("HUAWEI");
                break;
        }
        if (PushUtils.DEBUG) {
            Log.d(TAG, "InkePushHelper isSupportPush: " + pushType + " - " + support);
        }
        return support;
    }

    /**
     * 判断华为emui等级是否大于5.0.0
     * https://developer.huawei.com/consumer/cn/help/60103
     *
     * @return
     */
    public static boolean emuiLevelAboveFive() {
        int emuiApiLevel = 0;
        try {
            Class cls = Class.forName("android.os.SystemProperties");
            Method method = cls.getDeclaredMethod("get", new Class[]{String.class});
            emuiApiLevel = Integer.parseInt((String) method.invoke(cls, new Object[]{"ro.build.hw_emui_api_level"}));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return emuiApiLevel > 10;
    }

    /**
     * 是否安装华为移动服务
     *
     * @param context
     * @return
     */
    public static boolean isInStallHMS(Context context) {
        if (context == null) {
            return false;
        }
        PackageInfo pi;
        PackageManager pm = context.getPackageManager();
        try {
            pi = pm.getPackageInfo("com.huawei.hwid", 0);
            return pi != null;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void sendBroadcast(Context context, ReceiverType receiverType, ReceiverInfo receiverInfo) {
        if (null == context || null == receiverType || null == receiverInfo) {
            Log.e(TAG, "push消息参数错误：content=" + context + ",receiverType=" + receiverType + ",receiverInfo=" + receiverInfo);
            return;
        }
        Intent intent = new Intent();
        intent.putExtra(Constance.RECEIVER_TYPE, receiverType);
        intent.putExtra(Constance.RECEIVER_INFO, receiverInfo);
        intent.setAction(Constance.ACTION);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            context.sendBroadcast(intent, context.getPackageName() + Constance.PERMISSION);
        } else {
            sendImplicitBroadcast(context, intent);
        }
    }

    private static void sendImplicitBroadcast(Context context, Intent intent) {
        PackageManager manager = context.getPackageManager();
        List<ResolveInfo> resolveInfos = manager.queryBroadcastReceivers(intent, 0);
        for (ResolveInfo resolveInfo : resolveInfos) {
            ComponentName componentName = new ComponentName(resolveInfo.activityInfo.applicationInfo.packageName,
                    resolveInfo.activityInfo.name);
            intent.setComponent(componentName);
            context.sendBroadcast(intent, context.getPackageName() + Constance.PERMISSION);
        }
    }

    /**
     * 检测是否开启了通知开关
     * areNotificationsEnabled 只对 API 19 及以上版本有效，低于API 19 会一直返回true
     *
     * @param context
     * @return
     */
    public static boolean isNotificationEnabled(Context context) {
        if (context == null) {
            return true;
        }
        return NotificationManagerCompat.from(context.getApplicationContext()).areNotificationsEnabled();
    }

    /**
     * 引导跳转开启通知开关
     * https://blog.csdn.net/abc6368765/article/details/90270064
     *
     * @param activity
     */
    public static void openPushSwitch(Activity activity) {
        if (activity == null) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
            intent.putExtra(Settings.EXTRA_APP_PACKAGE, activity.getPackageName());
            intent.putExtra(Settings.EXTRA_CHANNEL_ID, activity.getApplicationInfo().uid);
            activity.startActivity(intent);
        } else {
            toPermissionSetting(activity);
        }
    }

    /**
     * 跳转到权限设置
     *
     * @param activity
     */
    private static void toPermissionSetting(Activity activity) {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
            toSystemConfig(activity);
        } else {
            try {
                toApplicationInfo(activity);
            } catch (Exception e) {
                e.printStackTrace();
                toSystemConfig(activity);
            }
        }
    }

    /**
     * 应用信息界面
     *
     * @param activity
     */
    private static void toApplicationInfo(Activity activity) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        localIntent.setData(Uri.fromParts("package", activity.getPackageName(), null));
        activity.startActivity(localIntent);
    }

    /**
     * 系统设置界面
     *
     * @param activity
     */
    private static void toSystemConfig(Activity activity) {
        try {
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            activity.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
